import React, { Component } from 'react';
import {
    Text,
    View,
    TextInput,
    TouchableOpacity
} from 'react-native';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
//加载模块样式
import { Loginstyles as styles } from '../../../../styles'
import Icon from 'react-native-vector-icons/Ionicons';
import Timer2 from '../../../util/Timer2'

import { NavigationActions } from 'react-navigation';
import { loginForPhone , sendCode } from '../../../actions/userAction'
import { myAlert } from '../../../util/compatible'
import stirageUtil from '../../../util/AsyncStorageUtil'
import { header,header2,header3 } from '../../../util/fetch'

// 获取当前设备的宽度
const Dimensions = require('Dimensions');
const { width, height } = Dimensions.get('window');

class Phone extends Component {
    phone = false;
    code = false;

    constructor(props){
        super(props);
        this.state = ({
            //验证码是否可用
            isToCode:false,
            //登录按钮是否可用
            isOk: false,
            //是否等待
            isloading: false,
            //跳过
            isPass:false
        });
    }

    isOKP(val){
        if(val.length>=11){
            this.phone = true
        }else{
            this.phone = false
        }
        this.setState({isToCode:this.phone})
        this.isOk()
    }

    isOKC(val){
        if(val.length>=3){
            this.code = true
        }else{
            this.code = false
        }
        this.isOk()
    }

    isOk(){
        if(this.phone && this.code){
                this.setState({isOk:true})
            }else{
                this.setState({isOk:false})
        }
    }

    goLogin() {
        if (this.state.isOk) {
            this.setState(
                {   isloading: true,
                    isOk: false,
                    isPass: true
                })
            this.props.actions.loginForPhone({
                loginPhone: this.refs.phone._lastNativeText,
                loginPhoneKey: this.refs.code._lastNativeText
            });
        }

    }
    
    componentDidUpdate() {
        if(this.props.loginData.statusText=="err"&&this.state.isloading==true){
            myAlert("网络连接失败！")
            this.setState({isOk:true,isloading:false})
        }
        if(this.props.sendData.statusText=="err"){
            myAlert("网络连接失败！")
        }else if(this.props.sendData.statusText=="ok"){
            if(this.props.sendData.data.sendMsg&&this.props.sendData.data.sendMsg.stat!="100"){
                myAlert("验证码发送失败，请检查后重新发送")
            }else if(this.props.sendData.data.msg=="miss"){
                myAlert("账号还未注册")
            }
        }
    }

    componentWillUnmount(){
        this.state.isPass = false
    }

    componentWillReceiveProps(nextProps) {
        const { data } = nextProps.loginData
        if (data.msg != "" && this.state.isPass) {//有后台消息并且是login触发的props改变
            //登录成功
            if (data.msg == "ok") {
                //保存token
                stirageUtil.save("userType", data.userType).then(()=>{
                    //保存token
                    stirageUtil.save("accountToken", data.token).then(() => {
                        header.accessToken = data.token
                        header2.accessToken = data.token
                        header3.accessToken = data.token
                        this.passing()
                    });
                })
            } else {
                //失败弹出消息
                myAlert(data.msg)
            }
            this.setState({ isOk: true, isloading: false })
        }
    }

    passing() {
        resetAction = NavigationActions.reset({
            index: 0,
            actions: [
                NavigationActions.navigate({ routeName: 'App' })//要跳转到的页面名字
            ]
        });
        this.props.navigation.dispatch(resetAction);
    }

    render() {
        return (
            <View style={styles.container}>

                {/** 输入框容器 */}
                <View style={[styles.textInputContianer, { width: width * 0.85 }]}>

                    {/** 手机号输入框 */}
                    <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'center' }}>
                        <Icon
                            name={'md-phone-portrait'}
                            size={22}
                            color={'#ffffff'} style={styles.ImageStyle} />

                        <TextInput
                            ref="phone"
                            placeholder="请输入手机号"
                            clearButtonMode="always"
                            underlineColorAndroid="transparent"
                            onChangeText={this.isOKP.bind(this)}
                            style={[styles.textInputStylePhoneNum, { width: width * 0.85 }]}>
                        </TextInput>
                        <Timer2 t={60} ready={this.state.isToCode} rollBack={()=>{
                            if(this.state.isToCode){
                                this.props.actions.sendCode({
                                    phone: this.refs.phone._lastNativeText,
                                });
                            }
                        }}/>
                    </View>
                    {/** 分割线 */}
                    <View style={styles.dividingLine} />
                    <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'center' }}>
                        <Icon
                            name={'md-text'}
                            size={22}
                            color={'#ffffff'} style={styles.ImageStyle} />
                        {/** 密码输入框 */}
                        <TextInput
                            ref="code"
                            placeholder="请输入验证码"
                            style={[styles.textInputStylePWD, { width: width * 0.85 }]}
                            password={true}
                            onChangeText={this.isOKC.bind(this)}
                            clearButtonMode="always"
                            underlineColorAndroid="transparent">
                        </TextInput>
                        {/* <Timer2 t={60} rollBack={()=>{
                            if(this.state.isToCode){
                                this.props.actions.sendCode({
                                    phone: this.refs.phone._lastNativeText,
                                });
                            }
                        }}/> */}
                    </View>
                </View>
                {/*登录按钮*/}
                <TouchableOpacity
                    activeOpacity={1}
                    // 按事件(按下和抬起)
                    // onPress={() => {}}
                    style={this.state.isOk ? [styles.loginBtnStyle, { width: width * 0.85 ,
                    elevation: 3,
                    shadowColor: 'black',
                    shadowOpacity: 1,
                    shadowRadius: 5}] : [styles.loginBtnStyle, { backgroundColor: "#aeaeae", width: width * 0.85,
                    elevation: 3,
                    shadowColor: 'black',
                    shadowOpacity: 1,
                    shadowRadius: 5 }]}
                        onPress={this.goLogin.bind(this)}>
                    <Text style={{ color: '#fff', fontSize: 17 }}>
                        {this.state.isloading ? "等  待" : "登  录"}
                    </Text>
                </TouchableOpacity>

                <TouchableOpacity style={[styles.forgetpasStyle, { width: width * 0.8 }]}
                onPress={() => { this.props.navigation.navigate('Validate') }}>
                    {/*左边*/}
                    <Text style={{ color: '#cccccc',fontFamily:"msyh",fontSize:12 }}>忘记密码?</Text>
                </TouchableOpacity>
            </View>
        )
    }
}

//组合action
var actions = {
    loginForPhone,sendCode
}
//连接state到props
const mapStateToProps = state => {
    return {
        loginData: state.loginPhoneReducer,
        sendData: state.sendCodeReducer
    }
}
//连接action
const mapDispatchToProps = (dispatch) => {
    return {
        actions: bindActionCreators(actions, dispatch)
    }
}
//导出组合好的组件(组合后状态改变重新渲染组合组件的页面)
export default connect(
    mapStateToProps, mapDispatchToProps
)(Phone);
